<template>
  <div>
    <a-modal
      v-model:visible="visible"
      :title="enrollParams.enrollId ? '修改报名信息' : '添加报名信息'"
      @cancel="visible = false"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="enrollParams" ref="formRef">
        <a-form-item
          field="enrollTitle"
          label="报名标题"
          :rules="[{ required: true, message: '报名标题不能为空' }]"
          validate-trigger="blur"
        >
          <a-input
            style="width: 350px"
            v-model="enrollParams.enrollTitle"
            placeholder="请输入报名标题"
          />
        </a-form-item>

        <a-form-item
          field="enrollPersonNum"
          label="报名人数"
          :rules="[{ required: true, message: '报名人数不能为空' }]"
          validate-trigger="blur"
        >
          <a-input-number
            v-model="enrollParams.enrollPersonNum"
            :style="{ width: '350px' }"
            placeholder="Please Enter"
            class="input-demo"
            :min="10"
            :max="100"
          />
        </a-form-item>

        <a-form-item
          field="enrollImg"
          label="报名图片"
          :rules="[{ required: true, message: '报名图片不能为空' }]"
          validate-trigger="blur"
        >
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            image-preview
            :limit="1"
            @before-upload="beforeUpload"
          />
        </a-form-item>

        <a-form-item
          field="enrollPersonNum"
          label="报名时间"
          :rules="[{ required: true, message: '报名时间不能为空' }]"
          validate-trigger="blur"
        >
          <a-range-picker
            style="width: 350px; margin: 0 24px 24px 0"
            show-time
            :time-picker-props="{ defaultValue: ['12:12:12', '12:12:12'] }"
            format="YYYY-MM-DD HH:mm"
            show-clear
            v-model="dateRange"
            @change="onDateRangeChange"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-card>
      <a-space size="medium">
        <a-input-search
          :style="{ width: '280px' }"
          placeholder="请输入报名标题"
          search-button
          @search="getErollListByTitle"
          v-model="keyword"
        />
        <a-button @click="openVisible" type="primary">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>添加信息</template>
        </a-button>
        <a-popconfirm content="你确定要删除这些用户吗?" @ok="batchDelete">
          <a-button type="primary" status="danger">
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-popconfirm>
      </a-space>
    </a-card>
    <a-card>
      <a-table
        :data="enrollInfoArr"
        :bordered="{ cell: true }"
        :pagination="false"
        row-key="enrollId"
        :rowSelection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }"
        v-model:selectedKeys="selectEroll"
      >
        <template #columns>
          <a-table-column
            title="报名标题"
            data-index="enrollTitle"
          ></a-table-column>
          <a-table-column
            title="报名人数"
            data-index="enrollPersonNum"
          ></a-table-column>
          <a-table-column
            title="目前人数"
            data-index="currentPersonNum"
          ></a-table-column>
          <a-table-column title="报名开始时间" data-index="enrollStartTime">
            <template #cell="{ record }">
              {{ formattedDate(record.enrollStartTime) }}
            </template>
          </a-table-column>
          <a-table-column title="报名截止时间" data-index="enrollEndTime">
            <template #cell="{ record }">
              {{ formattedDate(record.enrollEndTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-space>
                <a-button @click="editEroll(record)" type="outline" size="mini">
                  <template #icon>
                    <icon-edit />
                  </template>
                  <template #default>编辑</template>
                </a-button>
                <a-popconfirm
                  @ok="deleteEroll(record.enrollId)"
                  content="你确定要删除吗?"
                >
                  <a-button size="mini" status="danger">
                    <template #icon>
                      <icon-delete />
                    </template>
                    <template #default>删除</template>
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <a-pagination
        @change="getEnrollInfo"
        @page-size-change="pageSizeChange"
        style="margin-top: 15px"
        :total="total"
        show-total
        show-page-size
        :page-size="pageSize"
        :current="pageNo"
      />
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  reqEnrollInfoList,
  reqEnrollByTitle,
  reqBatchDeleteEnrollInfo,
  addOrUpdateEnrollInfo,
  reqDeleteEnrollById,
} from '@/api/enroll/index'
import { IconDelete, IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { EnrollParams } from '@/api/enroll/type'
import { Message } from '@arco-design/web-vue'
import { reqUploadImage } from '@/api/publicApi'

// import { UploadRequest } from '@arco-design/web-vue';
let enrollInfoArr = ref([])
let total = ref<number>(0)
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let keyword = ref<String>()
let selectEroll = ref([])
let formRef = ref()
let dateRange = ref()
const visible = ref(false)
const fileList = ref([])

const enrollParams: EnrollParams = reactive({
  enrollId: 0,
  enrollTitle: '',
  enrollImg: '',
  enrollPersonNum: 50,
  currentPersonNum: 0,
  enrollStartTime: [],
  enrollEndTime: [],
})

onMounted(() => {
  getEnrollInfo()
})

function onDateRangeChange(value: any) {
  if (!value || value.length !== 2) {
    // 日期范围被清空的处理逻辑
  }
  dateRange.value = value
}

// 文件上传成功的回调
const beforeUpload = async (file: File) => {
  const forms = new FormData()
  forms.append('image', file) // 获取上传图片信息
  let result = await reqUploadImage(forms) //上传图片至和后台文件中
  let obj = {
    url: getImageUrl(result), //格式化图片路径
  }
  fileList.value.push(obj) //将图片路径添加到fileList中
}

// 格式化图片路径
const getImageUrl = (imageUrl: any) => {
  if (imageUrl) {
    // 拼接后端服务器地址和图片地址
    return `http://localhost:8081${imageUrl}`
  }
}

// 获取用户数据
const getEnrollInfo = async (pager = 1) => {
  // 收集当前的页码
  pageNo.value = pager
  let result: any = await reqEnrollInfoList(pageNo.value, pageSize.value)
  console.log('这是页码？？？' + result.data.records)

  if (result.status === 'OK') {
    enrollInfoArr.value = result.data.records
    total.value = result.data.total
  }
}
// 页码改变
const pageSizeChange = (value: number) => {
  pageSize.value = value
  getEnrollInfo(pageNo.value)
}

// 通过标题搜索
const getErollListByTitle = async () => {
  if (keyword.value) {
    let result: any = await reqEnrollByTitle(
      pageNo.value,
      pageSize.value,
      keyword.value,
    )
    if (result.status === 'OK') {
      enrollInfoArr.value = result.data.records
    }
  } else {
    getEnrollInfo()
  }
}

// 模态框点击确定
const handleBeforeOk = () => {
  enrollParams.enrollStartTime = convertStringToTimeArray(dateRange.value[0])
  enrollParams.enrollEndTime = convertStringToTimeArray(dateRange.value[1])
  enrollParams.enrollImg = fileList.value[0].url
  formRef.value.validate(async (r: any, _Record: any) => {
    if (r === undefined) {
      // 发送请求
      let result = await addOrUpdateEnrollInfo(enrollParams)
      if (result.status === 'OK') {
        Message.success(result.message)
        getEnrollInfo()
        visible.value = false
      } else {
        Message.error(result.message)
      }
    }
  })
}

function convertStringToTimeArray(dateTimeStr: string): number[] {
  // 创建Date对象
  const date = new Date(dateTimeStr)

  // 获取年、月、日、小时、分钟、秒，并注意JavaScript中月份是从0开始的，所以要加1
  const year = date.getFullYear()
  const month = date.getMonth() + 1 // 月份从0开始计数，所以需要+1
  const day = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()

  // 将获取到的时间部分组成数组并返回
  return [year, month, day, hours, minutes, seconds]
}

// 格式化时间戳
const formattedDate = (dateParts: any) => {
  let date = new Date(
    dateParts[0],
    dateParts[1] - 1,
    dateParts[2],
    dateParts[3],
    dateParts[4],
    dateParts[5],
  )
  // 转换为格式化的日期字符串
  let year = date.getFullYear()
  let month = ('0' + (date.getMonth() + 1)).slice(-2)
  let day = ('0' + date.getDate()).slice(-2)

  return `${year}-${month}-${day}`
}

// 打开模态框
const openVisible = () => {
  Object.assign(enrollParams, {
    enrollId: 0,
    enrollTitle: '',
    enrollImg: '',
    enrollPersonNum: 50,
    currentPersonNum: '',
    enrollStartTime: '',
    enrollEndTime: '',
  })
  dateRange.value = ['', '']
  fileList.value = []

  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
  visible.value = true
}

const editEroll = (_record: any) => {
  fileList.value = []
  Object.assign(enrollParams, _record)
  if (_record.enrollImg !== '') {
    fileList.value[0] = {
      url: _record.enrollImg,
    }
  }
  visible.value = true
}

const deleteEroll = async (_recordId: any) => {
  let result: any = await reqDeleteEnrollById(_recordId)
  if (result.status === 'OK') {
    Message.success(result.message)
    getEnrollInfo(
      enrollInfoArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}
// 批量删除
const batchDelete = async () => {
  if (selectEroll.value.length < 1) {
    Notification.warning({
      title: '删除提示',
      content: '请选择你要删除的用户!',
    })
    return
  }
  let result = await reqBatchDeleteEnrollInfo(selectEroll.value)
  if (result.status === 'OK') {
    Message.success(result.message)
    getEnrollInfo(pageNo.value)
  }
}
</script>

<style lang="scss" scoped></style>
